FROM ros/melodic:desktop

ARG NUM_THREADS=16
ARG LIBS_DIR=/home/openlib
ARG LEGO_LOAM_WS_DIR=/home/slam/lego_loam_ws

RUN set -x \
  && mkdir -p ${LIBS_DIR} \
  && mkdir -p ${LEGO_LOAM_WS_DIR} \
  && chmod 777 -R ${LIBS_DIR} \
  && chmod 777 -R ${LEGO_LOAM_WS_DIR}

RUN set -x \
  && apt-get update \
  && apt-get install -y --no-install-recommends wget nano unzip build-essential \
    libomp-dev python3-pip libmetis-dev ros-melodic-pcl-ros ros-melodic-image-transport \
  && apt-get clean \
  && rm -rf /var/lib/apt/lists/*

ARG GTSAM_VERSION=4.0.0-alpha2
COPY gtsam-${GTSAM_VERSION}.zip ${LIBS_DIR}/
WORKDIR ${LIBS_DIR}/
RUN set -x \
  && unzip -q gtsam-${GTSAM_VERSION}.zip \
  && rm -rf gtsam-${GTSAM_VERSION}.zip \
  && cd gtsam-${GTSAM_VERSION} \
  && mkdir -p build \
  && cd build \
  && cmake .. \
  && make -j${NUM_THREADS} \
  && make install \
  && rm -rf ${LIBS_DIR}/gtsam-${GTSAM_VERSION}

ARG LEGO_VERSION=master
RUN mkdir -p ${LEGO_LOAM_WS_DIR}/src
WORKDIR ${LEGO_LOAM_WS_DIR}/src
RUN /bin/bash -c '. /opt/ros/melodic/setup.bash; catkin_init_workspace'

RUN sed -i '9c #include "lz4.h"' /usr/include/flann/util/serialization.h
RUN sed -i '10c #include "lz4hc.h"' /usr/include/flann/util/serialization.h

COPY LeGO-LOAM-${LEGO_VERSION}.zip ${LEGO_LOAM_WS_DIR}/src/
WORKDIR ${LEGO_LOAM_WS_DIR}/src/
RUN set -x \
  && unzip -q LeGO-LOAM-${LEGO_VERSION}.zip \
  && rm -rf LeGO-LOAM-${LEGO_VERSION}.zip \
  && mv ${LEGO_LOAM_WS_DIR}/src/LeGO-LOAM-${LEGO_VERSION}/* ${LEGO_LOAM_WS_DIR}/src/ \
  && rm -rf ${LEGO_LOAM_WS_DIR}/src/LeGO-LOAM-${LEGO_VERSION}

WORKDIR ${LEGO_LOAM_WS_DIR}
RUN /bin/bash -c '. /opt/ros/melodic/setup.bash; catkin_make -j1 -DCMAKE_BUILD_TYPE=Release'

# entrypoint file
COPY entrypoint.sh /home/

RUN chmod 777 /home/entrypoint.sh
RUN chmod 777 -R ${LEGO_LOAM_WS_DIR}

WORKDIR /home

ENTRYPOINT ["/home/entrypoint.sh"]
